import React, { useState, useRef, useEffect } from 'react';
import { 
  Eye, 
  ZoomIn, 
  ZoomOut, 
  RotateCw, 
  Maximize2, 
  Grid3X3, 
  Palette,
  Download,
  RefreshCw,
  AlertTriangle
} from 'lucide-react';

const SvgPreview = ({ svgCode }) => {
  const [scale, setScale] = useState(1);
  const [rotation, setRotation] = useState(0);
  const [background, setBackground] = useState('transparent');
  const [showGrid, setShowGrid] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [error, setError] = useState(null);
  const previewRef = useRef(null);
  const containerRef = useRef(null);

  const backgrounds = [
    { name: '透明', value: 'transparent', class: 'bg-transparent' },
    { name: '白色', value: 'white', class: 'bg-white' },
    { name: '黑色', value: 'black', class: 'bg-black' },
    { name: '灰色', value: 'gray', class: 'bg-gray-100' },
    { name: '棋盘', value: 'checkered', class: 'bg-checkered' }
  ];

  // 验证 SVG 代码
  useEffect(() => {
    if (!svgCode.trim()) {
      setError(null);
      return;
    }

    try {
      const parser = new DOMParser();
      const doc = parser.parseFromString(svgCode, 'image/svg+xml');
      const errorNode = doc.querySelector('parsererror');
      
      if (errorNode) {
        setError('SVG 代码格式错误');
      } else if (!svgCode.includes('<svg')) {
        setError('请输入有效的 SVG 代码');
      } else {
        setError(null);
      }
    } catch (err) {
      setError('解析 SVG 时出错');
    }
  }, [svgCode]);

  const handleZoomIn = () => {
    setScale(prev => Math.min(prev + 0.2, 3));
  };

  const handleZoomOut = () => {
    setScale(prev => Math.max(prev - 0.2, 0.2));
  };

  const handleRotate = () => {
    setRotation(prev => (prev + 90) % 360);
  };

  const handleReset = () => {
    setScale(1);
    setRotation(0);
  };

  const handleFullscreen = () => {
    if (!document.fullscreenElement) {
      containerRef.current?.requestFullscreen();
      setIsFullscreen(true);
    } else {
      document.exitFullscreen();
      setIsFullscreen(false);
    }
  };

  const handleDownloadPNG = async () => {
    if (!svgCode.trim() || error) return;

    try {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      const img = new Image();
      
      const svgBlob = new Blob([svgCode], { type: 'image/svg+xml;charset=utf-8' });
      const url = URL.createObjectURL(svgBlob);
      
      img.onload = () => {
        canvas.width = img.width || 300;
        canvas.height = img.height || 300;
        
        if (background !== 'transparent') {
          ctx.fillStyle = background === 'white' ? '#ffffff' : 
                         background === 'black' ? '#000000' : '#f3f4f6';
          ctx.fillRect(0, 0, canvas.width, canvas.height);
        }
        
        ctx.drawImage(img, 0, 0);
        
        canvas.toBlob(blob => {
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = 'svg-preview.png';
          link.click();
          URL.revokeObjectURL(link.href);
        });
        
        URL.revokeObjectURL(url);
      };
      
      img.src = url;
    } catch (err) {
      console.error('下载失败：', err);
    }
  };

  const getBackgroundClass = () => {
    switch (background) {
      case 'white': return 'bg-white';
      case 'black': return 'bg-black';
      case 'gray': return 'bg-gray-100';
      case 'checkered': return 'bg-checkered';
      default: return 'bg-transparent';
    }
  };

  return (
    <div 
      ref={containerRef}
      className={`bg-white rounded-2xl shadow-xl border border-gray-200/50 overflow-hidden ${isFullscreen ? 'fixed inset-0 z-50 rounded-none' : ''}`}
    >
      {/* 预览头部 */}
      <div className="bg-gray-50/50 px-4 py-3 border-b border-gray-200/50">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <Eye className="w-5 h-5 text-gray-600" />
            <h3 className="font-semibold text-gray-900">SVG 预览</h3>
            {error && (
              <div className="flex items-center space-x-1 text-red-600">
                <AlertTriangle className="w-4 h-4" />
                <span className="text-sm">{error}</span>
              </div>
            )}
          </div>
          
          <div className="flex items-center space-x-2">
            {/* 背景选择 */}
            <div className="relative">
              <select
                value={background}
                onChange={(e) => setBackground(e.target.value)}
                className="px-3 py-1.5 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
              >
                {backgrounds.map(bg => (
                  <option key={bg.value} value={bg.value}>{bg.name}</option>
                ))}
              </select>
            </div>
            
            {/* 网格切换 */}
            <button
              onClick={() => setShowGrid(!showGrid)}
              className={`flex items-center space-x-1 px-3 py-1.5 text-sm rounded-lg transition-colors ${
                showGrid 
                  ? 'text-blue-600 bg-blue-50' 
                  : 'text-gray-600 hover:text-blue-600 hover:bg-blue-50'
              }`}
            >
              <Grid3X3 className="w-4 h-4" />
              <span>网格</span>
            </button>
            
            {/* 缩放控制 */}
            <div className="flex items-center space-x-1 bg-gray-100 rounded-lg p-1">
              <button
                onClick={handleZoomOut}
                className="p-1 hover:bg-white rounded transition-colors"
              >
                <ZoomOut className="w-4 h-4" />
              </button>
              <span className="px-2 text-sm font-medium min-w-[3rem] text-center">
                {Math.round(scale * 100)}%
              </span>
              <button
                onClick={handleZoomIn}
                className="p-1 hover:bg-white rounded transition-colors"
              >
                <ZoomIn className="w-4 h-4" />
              </button>
            </div>
            
            {/* 旋转 */}
            <button
              onClick={handleRotate}
              className="flex items-center space-x-1 px-3 py-1.5 text-sm text-gray-600 hover:text-purple-600 hover:bg-purple-50 rounded-lg transition-colors"
            >
              <RotateCw className="w-4 h-4" />
              <span>{rotation}°</span>
            </button>
            
            {/* 重置 */}
            <button
              onClick={handleReset}
              className="flex items-center space-x-1 px-3 py-1.5 text-sm text-gray-600 hover:text-green-600 hover:bg-green-50 rounded-lg transition-colors"
            >
              <RefreshCw className="w-4 h-4" />
              <span>重置</span>
            </button>
            
            {/* 下载 PNG */}
            <button
              onClick={handleDownloadPNG}
              disabled={!svgCode.trim() || error}
              className="flex items-center space-x-1 px-3 py-1.5 text-sm text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Download className="w-4 h-4" />
              <span>PNG</span>
            </button>
            
            {/* 全屏 */}
            <button
              onClick={handleFullscreen}
              className="flex items-center space-x-1 px-3 py-1.5 text-sm text-gray-600 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
            >
              <Maximize2 className="w-4 h-4" />
              <span>全屏</span>
            </button>
          </div>
        </div>
      </div>

      {/* 预览区域 */}
      <div className={`relative ${isFullscreen ? 'h-full' : 'h-96'} overflow-hidden`}>
        <div 
          ref={previewRef}
          className={`w-full h-full flex items-center justify-center relative ${getBackgroundClass()}`}
          style={{
            backgroundImage: background === 'checkered' ? 
              'linear-gradient(45deg, #f0f0f0 25%, transparent 25%), linear-gradient(-45deg, #f0f0f0 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #f0f0f0 75%), linear-gradient(-45deg, transparent 75%, #f0f0f0 75%)' : 
              'none',
            backgroundSize: background === 'checkered' ? '20px 20px' : 'auto',
            backgroundPosition: background === 'checkered' ? '0 0, 0 10px, 10px -10px, -10px 0px' : 'auto'
          }}
        >
          {/* 网格 */}
          {showGrid && (
            <div className="absolute inset-0 opacity-20 pointer-events-none">
              <svg width="100%" height="100%" className="w-full h-full">
                <defs>
                  <pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">
                    <path d="M 20 0 L 0 0 0 20" fill="none" stroke="#666" strokeWidth="1"/>
                  </pattern>
                </defs>
                <rect width="100%" height="100%" fill="url(#grid)" />
              </svg>
            </div>
          )}
          
          {/* SVG 预览 */}
          {svgCode.trim() && !error ? (
            <div
              className="flex items-center justify-center transition-all duration-300"
              style={{
                transform: `scale(${scale}) rotate(${rotation}deg)`,
                transformOrigin: 'center'
              }}
              dangerouslySetInnerHTML={{ __html: svgCode }}
            />
          ) : (
            <div className="text-center py-12">
              {error ? (
                <div className="text-red-500">
                  <AlertTriangle className="w-12 h-12 mx-auto mb-4" />
                  <p className="text-lg font-medium mb-2">预览出错</p>
                  <p className="text-sm">{error}</p>
                </div>
              ) : (
                <div className="text-gray-400">
                  <Eye className="w-12 h-12 mx-auto mb-4" />
                  <p className="text-lg font-medium mb-2">SVG 预览</p>
                  <p className="text-sm">在左侧输入 SVG 代码即可实时预览</p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* 底部信息栏 */}
      <div className="bg-gray-50/50 px-4 py-2 border-t border-gray-200/50">
        <div className="flex items-center justify-between text-xs text-gray-500">
          <div className="flex items-center space-x-4">
            <span>缩放：{Math.round(scale * 100)}%</span>
            <span>旋转：{rotation}°</span>
            <span>背景：{backgrounds.find(bg => bg.value === background)?.name}</span>
          </div>
          <div className="flex items-center space-x-2">
            <span>实时预览已启用</span>
            <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SvgPreview;
